#pragma once

#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <stdlib.h>
#include <sys/fcntl.h>
#include<vector>

void SetNonBlock(int sock)
{
    // 将fd设置为非阻塞
    int fl = fcntl(sock, F_GETFL);
    if (fl < 0)
    {
        std::cerr << "fcntl" << std::endl;
        return;
    }
    fcntl(sock, F_SETFL, fl | O_NONBLOCK);
}

// 分包函数
void SplitSegment(std::string& buffer,std::vector<std::string>& tokens,std::string sep)
{
    while(true)
    {
        size_t pos = buffer.find(sep);
        if(pos != buffer.npos)
        {
            std::string token = buffer.substr(0,pos);// 左闭右开
            buffer.erase(0,pos+sep.size());
            tokens.push_back(token);
        }
        else
        {
            break;
        }
    }
}

// 反序列化函数
bool Deserialize(const std::string seg,std::string* out1,std::string* out2)
{
    std::string op = "+";
    auto pos = seg.find(op);
    if(pos == std::string::npos)
    {
        return false;
    }
    *out1 = seg.substr(0,pos);
    *out2 = seg.substr(pos+op.size());
    return true;
}